import { MapConfig, defaultMapConfig } from './config/MapConfig';
import { Building } from './Building';
import { Terrain } from './Terrain';
const { regClass, property } = Laya;

@regClass()
export class MapEditor extends Laya.Script {
    @property(Laya.Box)
    public box_map: Laya.Box = null;

    @property(Laya.Box)
    public box_game: Laya.Box = null;

    @property(Laya.Button)
    public btn_load: Laya.Button = null;

    @property(Laya.Button)
    public btn_save: Laya.Button = null;

    @property(Laya.Button)
    public btn_new: Laya.Button = null;

    private currentConfig: MapConfig = defaultMapConfig;
    private fileInput: HTMLInputElement;

    onAwake(): void {
        this.initUI();
        this.initEvents();
    }

    private initUI(): void {
        // 创建文件输入元素
        this.fileInput = document.createElement('input');
        this.fileInput.type = 'file';
        this.fileInput.accept = '.json';
        this.fileInput.style.display = 'none';
        document.body.appendChild(this.fileInput);
    }

    private initEvents(): void {
        // 加载配置按钮
        if (this.btn_load) {
            this.btn_load.on(Laya.Event.CLICK, this, this.onLoadClick);
        }

        // 保存配置按钮
        if (this.btn_save) {
            this.btn_save.on(Laya.Event.CLICK, this, this.saveMapConfig);
        }

        // 新建地图按钮
        if (this.btn_new) {
            this.btn_new.on(Laya.Event.CLICK, this, this.createNewMap);
        }

        // 文件选择事件
        this.fileInput.onchange = (e: Event) => {
            const target = e.target as HTMLInputElement;
            if (target.files && target.files[0]) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const config = JSON.parse(e.target?.result as string) as MapConfig;
                        this.loadMapConfig(config);
                    } catch (error) {
                        console.error('配置文件格式错误:', error);
                    }
                };
                reader.readAsText(target.files[0]);
            }
        };
    }

    private onLoadClick(): void {
        this.fileInput.click();
    }

    private loadMapConfig(config: MapConfig): void {
        this.currentConfig = config;
        this.clearMap();

        // 加载地形
        config.terrains.forEach(terrainConfig => {
            const terrain = new Terrain();
            terrain.initTerrain(terrainConfig);
            this.box_map.addChild(terrain);
        });

        // 加载建筑
        config.buildings.forEach(buildingConfig => {
            const building = new Building();
            building.initBuilding(buildingConfig, config.gridSize);
            this.box_map.addChild(building);
        });
    }

    private saveMapConfig(): void {
        const config: MapConfig = {
            terrains: [],
            buildings: [],
            mapSize: this.currentConfig.mapSize,
            gridSize: this.currentConfig.gridSize
        };
        let num = this.box_map.numChildren;
        for (let i = 0; i < num; i++) {
            const child = this.box_map.getChildAt(i);
            if (child instanceof Terrain) {
                config.terrains.push(child.getConfig());
            } else if (child instanceof Building) {

            }
        }
            // 收集地形配置
            // this.box_map.children.forEach(child => {
            //     if (child instanceof Terrain) {
            //         config.terrains.push(child.getConfig());
            //     } else if (child instanceof Building) {
            //         config.buildings.push(child.getConfig());
            //     }
            // });

            // 导出配置文件
            const blob = new Blob([JSON.stringify(config, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'map_config.json';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

    private createNewMap(): void {
        this.currentConfig = { ...defaultMapConfig };
        this.clearMap();
    }

    private clearMap(): void {
        this.box_map.removeChildren();
    }
}